package feishu

import (
	"context"
	"errors"
	"fmt"
	"time"

	"algo-sdk-go/common/constant"
	"algo-sdk-go/framework/middleware/http/client"
)

const (
	TextMsgType MsgType = "text"

	sendMsgFailedLog = "send msg failed"
)

var (
	ErrSendFailed = errors.New("消息发送失败")
)

type MsgType string

// Robot https://open.larksuite.com/document/client-docs/bot-v3/use-custom-bots-in-a-group
type Robot struct {
	url    string
	secret string
}

func NewFeiShuRobot(url, secret string) *Robot {
	return &Robot{
		url:    url,
		secret: secret,
	}
}

func (r *Robot) SendTextMessage(context string) (err error) {
	err = r.sendMsg(TextMsgType, &Msg{Text: context})
	return
}

func (r *Robot) sendMsg(msgType MsgType, content *Msg) (err error) {
	if r.url == "" {
		fmt.Println(sendMsgFailedLog, "msg", "url is empty")
		return
	}

	sec := time.Now().Unix()
	timestamp := fmt.Sprintf("%v", sec) // 解密种子
	// https://open.larksuite.com/document/client-docs/bot-v3/use-custom-bots-in-a-group
	sign, err := GenSign(r.secret, timestamp)
	if err != nil {
		return
	}

	body := client.ToRequestBody(WebhookRequest{
		Timestamp: timestamp,
		Sign:      sign,
		MsgType:   string(msgType),
		Content:   content,
	})

	resp, err := client.SendRequest[WebhookResponse](context.Background(), constant.HttpPost, r.url, body, nil)
	if err != nil {
		fmt.Println(sendMsgFailedLog, "url", r.url, "err", err)
		return
	}

	if resp.Code != 0 || resp.StatusCode != 0 {
		fmt.Println(sendMsgFailedLog, "url", r.url, "resp", resp)
		err = ErrSendFailed
	}
	return
}
